<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>react生命周期(新)</title>
    <style>
        .list {
            width: 200px;
            height: 150px;
            background-color: skyblue;
            overflow: auto;
        }
        .news {
            height: 30px;
        }
    </style>
</head>
<body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>


    <!-- 引入react核心库 -->
    <script src="../js/17/react.development.js" ></script>
    <!-- 引入react-dom，用于支持react操作DOM -->
    <script src="../js/17/react-dom.development.js"></script>
    <!-- 引入babel，用于将jsx转为js -->
    <script src="../js/babel.js" ></script>
    <script type="text/babel"> /*此处一定要写babel，否则无法识别jsx语法*/
        // 创建组件
        class NewsList extends React.Component {
            state = {
                newsArr: []
            }
            listRef = React.createRef()
            componentDidMount () {
                setInterval(() => {
                    const { newsArr } = this.state
                    const news = '新闻' + (newsArr.length + 1)
                    this.setState({
                        newsArr: [news, ...newsArr]
                    })
                }, 1000)
            }
            // 获取快照再更新之前
            getSnapshotBeforeUpdate () {
                console.log('count---getSnapshotBeforeUpdate')
                return this.listRef.current.scrollHeight
            }
            componentDidUpdate (prevProps, prevState, height) {
                this.listRef.current.scrollTop += this.listRef.current.scrollHeight - height
            }
            render () {
                return (
                    <div className="list" ref={this.listRef}>
                        {
                            this.state.newsArr.map((n, index) => {
                                return <div key={index} className="news">{n}</div>
                            })
                        }
                    </div>  
                )
            }
        }
        ReactDOM.render(<NewsList />, document.getElementById('test'))
    </script>
</body>
</html>